package com.fruit.service.lightpay.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fruit.constants.PayConstant;
import com.fruit.mapper.lightpay.LightPayMapper;
import com.fruit.mapper.pay.PayMapper;
import com.fruit.mapper.sys.SysMapper;
import com.fruit.pojo.lightpay.LightPayCashier;
import com.fruit.pojo.lightpay.LightPayCashierAlipay;
import com.fruit.pojo.pay.TransactionFlow;
import com.fruit.pojo.sys.AlipayConfig;
import com.fruit.pojo.sys.SysConfig;
import com.fruit.service.lightpay.LightPayManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

@Service("lightPayService")
public class LightPayService implements LightPayManager{

	
	@Autowired
	private PayMapper payMapper;
	
	@Autowired
	private SysMapper sysMapper;
	
	@Autowired
	private LightPayMapper lightPayMapper;	
	
	@Value("${alipay.money}")
	private String alipayMoney;
	
	@Value("${domain}")
	private String domain;
	
	public Map<String, Object> getTransactionFlow(String transactionCode){
		Map<String, Object> resMap = new HashMap<String, Object>();
		
		TransactionFlow tf = payMapper.getTransactionFlow(transactionCode);
		
		if(tf == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "交易订单不存在"));
			return resMap;
		}
		if(!PayConstant.State.notpay.equals(tf.getState())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "交易订单已取消或已支付"));
			return resMap;
		}
		
		resMap.put("price", tf.getPayPrice());
		resMap.put("transactionCode", transactionCode);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		return resMap;
		
	}

	public Map<String, Object> validation(LightPayCashier lpc){
		Map<String, Object> resMap = new HashMap<String, Object>();
		if(StringUtils.isEmpty(lpc.getTransactionCode())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "参数有误"));
			return resMap;	
		}
		//验证金额
		if(lpc.getPrice() == null || lpc.getPrice().compareTo(BigDecimal.ZERO) <= 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "支付金额有误"));
			return resMap;	
		}
		
		TransactionFlow tf = payMapper.getTransactionFlow(lpc.getTransactionCode());
		
		if(tf == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "交易订单不存在"));
			return resMap;
		}
		if(!PayConstant.State.notpay.equals(tf.getState())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "交易订单已取消或已支付"));
			return resMap;
		}
		if(lpc.getPrice().compareTo(tf.getPayPrice()) != 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "支付金额有误"));
			return resMap;	
		}
		
		
		AlipayConfig ac = sysMapper.getAlipayConfig();
		if(ac == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "系统异常"));
			return resMap;
		}
				
		resMap.put("ac", ac);
		resMap.put("tf", tf);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "校验成功"));
		
		return resMap;
		
	}
	
	@Override
	public Map<String, Object> saveAlipayPayCashier(LightPayCashier lpc) {

		Map<String, Object> resMap = new HashMap<String, Object>();
		//验证参数
		lpc.setPayMode(PayConstant.PayMode.alipay.getValue());
		resMap = validation(lpc);
		ResultInfo ri = (ResultInfo)resMap.get("result");
		if(ResultInfo.ERROR.equals(ri.getState()) ){
			return resMap;
		}
		AlipayConfig ac = (AlipayConfig)resMap.get("ac");
		TransactionFlow tf = (TransactionFlow)resMap.get("tf");
		String curTime = DateUtil.getTime();
		
		//插入收银记录
		lpc.setRemark(tf.getRemark());
		lpc.setCreateTime(curTime);
		lpc.setState(PayConstant.State.notpay.getValue());
		lightPayMapper.saveLightpayCashier(lpc);
		lpc.setCode(CustomUtil.orderCode(3, lpc.getId(), lpc.getUserId()));
		int num = lightPayMapper.updateLightpayCashierCode(lpc);
		if(num != 1){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
			return resMap;
		}

		
		LightPayCashierAlipay lpca = lightPayMapper.getLightpayCashierAlipay(lpc.getId());
		if(lpca == null){
			lpca = new LightPayCashierAlipay();
			lpca.setCashierId(lpc.getId());
			if(PayConstant.PayValue.test.equals(ac.getPayValue())){
				lpca.setTotalAmount(alipayMoney);
			}else{
				lpca.setTotalAmount(lpc.getPrice().toString());
			}
			lpca.setTimeStart(curTime);
			lpca.setSellerId(ac.getSellerId());
			lightPayMapper.saveLightpayCashierAlipay(lpca);
		}
		Map<String, String> returnParams = new HashMap<String, String>();
		returnParams.put("outTradeNo", lpc.getCode());
		returnParams.put("subject", lpc.getRemark());
		returnParams.put("totalAmount", lpca.getTotalAmount());
		returnParams.put("body", "共花费金额" + lpca.getTotalAmount() + "元");
		returnParams.put("appId", ac.getAppId());
		returnParams.put("returnUrl", domain+ac.getReturnUrl()+"?code="+lpc.getCode());
		returnParams.put("notifyUrl", domain+ac.getNotifyUrl());
		returnParams.put("sellerId", ac.getSellerId());
		returnParams.put("timeOutExpress", ac.getTimeOutExpress());
		returnParams.put("alipayPublicKey", ac.getAlipayPublicKey());
		returnParams.put("appPrivateKey", ac.getAppPrivateKey());
		returnParams.put("charset", ac.getCharset());
		returnParams.put("gateWayUrl", ac.getGateWayUrl());
		resMap.put("returnParams", returnParams);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		
		return resMap;
	}

	@Override
	public Map<String, Object> getLightpayCashierByCode(String code) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		LightPayCashier lpc = lightPayMapper.getLightpayCashierByCode(code);
		if(lpc == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "收银不存在"));
			return resMap;	
		}
		TransactionFlow tf = payMapper.getTransactionFlow(lpc.getTransactionCode());
		if(tf == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "交易流水不存在"));
			return resMap;	
		}
		
		resMap.put("tf", tf);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查看成功"));
		return resMap;
	}
	
	
}
